<template>
  <div class="comment-save">
    <el-input  v-model="commentDetail.title" placeholder="请输入标题" style="margin-bottom: 10px;"></el-input>
    <mavonEditor :toolbarsFlag = "true"
      :subfield = 'true'
      ref="md"
      v-model="commentDetail.text"
      v-bind="$attrs"
      v-on="$listeners"
      @imgAdd="handleImgAdd"
      style="min-height: 800px;"/>

    <div class="comment-footer">
      <span v-if="isAdmin()" >
       权重：<el-input v-model="commentDetail.weight" placeholder="权重" style="width: 100px;margin-right: 15px;"></el-input>

      </span>
      <span v-if="isAdmin()" >
        状态：<el-select v-model="commentDetail.status"  :placeholder="'状态'" style="width: 100px;margin-right: 15px;">
        <el-option label="可用" :value="0">可用</el-option>
        <el-option label="不可用" :value="1">不可用</el-option>
      </el-select>
      </span>

      <el-button type="success" @click="submitReply()" size="medium">保存</el-button>

    </div>
  </div>
</template>

<script>
import { mavonEditor } from 'mavon-editor';
import 'mavon-editor/dist/css/index.css';
import * as commentApi from '@/api/comment'
import {uploadImage} from "@/api/admin";
import {isRoot,isLogin,loginUser,removeToken,isAdmin} from '@/utils/auth'
export default {
  name: "saveOrUpdate",
  data(){
    return{
      commentDetail:{type:0},
    }
  },
  components: {
    mavonEditor,   //markdown编译器
  },
  methods:{
    isAdmin(){
      return isAdmin();
    },
    submitReply(){
      if(this.commentDetail.id){ //update
        commentApi.updateComment(this.commentDetail).then(res=>{
          if(res.data.success){
            this.$message({type:"success",message:"保存成功"});
            this.$router.push('/main/comment/detail/'+this.commentDetail.id);
          }
        })
      }else{  //保存
        commentApi.saveComment(this.commentDetail).then(res=>{
          if(res.data.success){
            this.$message({type:"success",message:"保存成功"});
            this.$router.push('/main/comment/detail/'+res.data.data.id);
          }
        })

      }

    },
    // 将图片上传到服务器，返回地址替换到md中
    async handleImgAdd(pos, file) {
      let form = new FormData();
      form.append('file', file);

      const res = await uploadImage(form).then(res=>{
        return '/api/user/download/'+res.data.data;
      })
      console.log(res);
      this.$refs.md.$img2Url(pos, res);
    },
  },
  created() {
    Object.assign(this.commentDetail,this.$route.query);
    if(this.commentDetail.id){ //修改，填入
      commentApi.getCommentDetail({"id":this.commentDetail.id}).then(res=>{
        if(res.data.data){
          this.commentDetail = res.data.data;
        }
      })
    }
  }
}
</script>

<style scoped>
.comment-save{
  width: 90%;
  text-align: center;
  margin: 0 auto;
}
.comment-save .comment-footer{
  position: absolute;
  bottom: 0px;
  left: 0px;
  width: 100%;
  background-color: white;
  z-index:1600;
  padding: 10px;
}
</style>